# -*- coding: utf-8 -*-

import configparser
import logging
import os
import sys

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from Cal_MACD import calMACD


config = configparser.ConfigParser()
config_file = 'config.ini'
if not os.path.exists(config_file):
    raise FileNotFoundError(f"Configuration file '{config_file}' not found.")


config.read(config_file)
DATA_DIR = config['DEFAULT'].get('DataDir', 'd:/Python/study_data')
LIST_DIR = config['DEFAULT'].get('List', 'list')
LOG_FILE = config['DEFAULT'].get('LogFile', 'log.txt')

if not os.path.exists(DATA_DIR):
    os.makedirs(DATA_DIR)

filelog = True
logger = logging.getLogger('log')
logger.setLevel(logging.DEBUG)
while logger.hasHandlers():
    for i in logger.handlers:
        logger.removeHandler(i)
# file log
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(message)s')

if filelog:
    fh = logging.FileHandler(LOG_FILE, encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    logger.addHandler(fh)


def test_stock(path):
    # 获取股票数据
    data = pd.read_csv(path)

    # 确保索引是日期时间类型
    if 'date' in data.columns:
        data.index = pd.to_datetime(data.date)
    else:
        raise ValueError("The 'date' column is missing from the data.")

    # 确保索引是日期时间类型
    data.index = pd.to_datetime(data.date)
    # 计算5日均线
    data['10_day_mavg'] = data['close'].rolling(window=10).mean()

    data['buy_signal'] = ((data['close'] < data['10_day_mavg'] * 1.03) &
                          (data['close'] >= data['10_day_mavg']) &
                          (data['close'].shift(1) > data['10_day_mavg'].shift(1)) &
                          (data['close'].shift(2) > data['10_day_mavg'].shift(2)) &
                          (data['close'].shift(3) > data['10_day_mavg'].shift(3)) &
                          (data['close'].shift(4) > data['10_day_mavg'].shift(4)) &
                          (data['close'].shift(5) > data['10_day_mavg'].shift(5)) &
                          (data['close'].shift(6) > data['10_day_mavg'].shift(6)) &
                          (data['close'].shift(7) > data['10_day_mavg'].shift(7)) &
                          (data['close'].shift(8) > data['10_day_mavg'].shift(8)) &
                          (data['close'].shift(9) > data['10_day_mavg'].shift(9)) &
                          (data['close'].shift(10) < data['10_day_mavg'].shift(10))
                          )

    # 检查生成的买入信号日期
    buy_signal_dates = data[data['buy_signal']].index
    buy_dict = {os.path.basename(path).split('.')[0]: [str(date)[:10] for date in buy_signal_dates]}

    return buy_dict


def find_all_buys(path):
    all_buys = {}
    list_df = pd.read_csv(f'{LIST_DIR}/stocks.csv')
    stocks = dict(zip(list_df['名称'], list_df['代码']))
    for name, code in stocks.items():
        if 'ST' not in name and 'bj' not in code and 'sz300' not in code and 'sh688' not in code:
            try:
                buys = test_stock(f'{DATA_DIR}/{path}/{code}.csv')
                for key, value in buys.items():
                    for date in value:
                        if date in all_buys:
                            all_buys[date].append(key)
                        else:
                            all_buys[date] = [key]
            except FileNotFoundError:
                continue

    all_buys_df = pd.DataFrame.from_dict(all_buys, orient='index').sort_index()
    all_buys_df.to_csv('all_buys_10_days.csv')


if __name__ == '__main__':
    find_all_buys('stocks')
